package algorithm.leetcode.simple;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 给定一个包含 n 个整数的数组 nums 和一个目标值 target，判断 nums 中是否存在四个元素 a，b，c 和 d 
 * 使得 a + b + c + d 的值与 target 相等
 *
 * @author jack.wu
 * @version 1.0
 * @date 2020/8/25
 */
public class Question18 {

    public static void main(String[] args) {
        Question18 question = new Question18();
        int[] nums = {0, 0, 0, 0};
        int target = 0;
        List<List<Integer>> lists = question.fourSum(nums, target);
        System.out.println(lists);
    }


    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> resultList = new ArrayList<>(10);
        List<Integer> result;
        if (nums == null || nums.length < 4) {
            return resultList;
        }
        Arrays.sort(nums);
        for (int i = 0; i <= nums.length - 4; i++) {
            for (int j = i + 1; j <= nums.length - 3; j++) {
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                int left = j + 1;
                int right = nums.length - 1;
                while (left < right) {
                    int temp = nums[i] + nums[j] + nums[left] + nums[right];
                    if (temp == target) {
                        result = Arrays.asList(nums[i], nums[j], nums[left], nums[right]);
                        resultList.add(result);
                        while (left < right && nums[left + 1] == nums[left]){
                            left++;
                        }
                        while (left < right && nums[right - 1] == nums[right]){
                            right--;
                        }
                        left++;
                        right--;
                    }else if (temp < target){
                        left++;
                    }else {
                        right--;
                    }
                }
            }
        }
        return resultList;
    }
}
